using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Scanner : MonoBehaviour
{
    public float scanRange; // 扫描范围
    public LayerMask targetLayer; // 目标层
    public RaycastHit2D[] targets; // 扫描到的目标
    public Transform nearestTarget; // 最近的目标

    void FixedUpdate()
    {
        targets = Physics2D.CircleCastAll(transform.position, scanRange, Vector2.zero, 0, targetLayer); // 在扫描范围内发射圆形光线，获取扫描到的目标
        nearestTarget = GetNearest();
    }

    // 获取最近的目标
    Transform GetNearest()
    {
        Transform result = null; // 初始化最近的目标为null
        float diff = scanRange; // 初始化最小距离为100，用于后面比较
        foreach (RaycastHit2D target in targets)
        {
            Vector3 myPos = transform.position; // 获取自身位置
            Vector3 targetPos = target.transform.position; // 获取目标位置
            float curDiff = Vector3.Distance(myPos, targetPos); // 计算自身与目标的距离
            if (curDiff < diff) // 如果当前目标距离比之前的最小距离还小，说明这个目标更近
            {
                diff = curDiff; // 更新最小距离
                result = target.transform; // 更新最近的目标
            }
        }
        return result; // 返回最近的目标
    }

    //场景窗口可视化射线
    private void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(transform.position, scanRange);
        Gizmos.color = Color.red;
    }
}

